//
//  WmcAlertViewProtocol.swift
//  YPWatermarkCamera
//
//  Created by 赵新 on 2022/8/6.
//

import UIKit
import YPBedrock

// MARK: - [WmcAlertViewProtocol]

protocol WmcAlertViewProtocol: NSObjectProtocol {}

private var k_presentVC = "k_presentVC"
private var k_willDismissBlock = "k_willDismissBlock"
private var k_didDismissBlock = "k_didDismissBlock"
extension WmcAlertViewProtocol {
    /// 该对象的WmcPresentVC
    private var presentVC: WmcPresentVC? {
        set { YPRuntime.Set(object: self, key:  &k_presentVC, value:  newValue) }
        get {
            let vc: WmcPresentVC? = YPRuntime.GetObject(self, key: &k_presentVC)
            return vc
        }
    }

    /// 即将消失回调
    var willDismissBlock: YPBlock.Empty? {
        set { YPRuntime.Set(object: self, key:  &k_willDismissBlock, value:  newValue) }
        get {
            let block: YPBlock.Empty? = YPRuntime.GetObject(self, key: &k_willDismissBlock)
            return block
        }
    }

    /// 即将消失回调
    var didDismissBlock: YPBlock.Empty? {
        set { YPRuntime.Set(object: self, key:  &k_didDismissBlock, value:  newValue) }
        get {
            let block: YPBlock.Empty? = YPRuntime.GetObject(self, key: &k_didDismissBlock)
            return block
        }
    }

    /// 展示视图
    /// - Parameter config: 配置
    func show(config: WmcPresentVC.Config,
              completion: YPBlock.Empty? = nil)
    {
        presentVC = WmcPresentVC(config: config)
        presentVC?.willTouchBackgroundDismissCompletionBlock = { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.willDismissBlock?()
        }
        presentVC?.didTouchBackgroundDismissCompletionBlock =  { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.didDismissBlock?()
        }
        presentVC?.show(completion)
    }

    /// 消失视图
    /// - Parameters:
    ///   - animated: 动画
    ///   - completion: 已经消失回调
    func dismiss(animated: Bool = true,
                 completion: YPBlock.Empty? = nil)
    {
        willDismissBlock?()
        // 弹窗消失
        presentVC?.dismiss(animated: animated, completion: { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.didDismissBlock?()
            completion?()
            weakSelf.presentVC = nil
        })
    }
}
